package com.mylib.libcore.network.interceptor;

import android.util.Log;

import com.mylib.libcore.AppContext;
import com.mylib.libcore.utils.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

import static com.mylib.libcore.config.NetConfig.NET_IS_LOCAL;

/**
 * 添加公共参数
 */
public class CommonParamInterceptor implements Interceptor {
    private final Charset UTF8 = Charset.forName("UTF-8");

    public CommonParamInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builderHeader = request.newBuilder();

        builderHeader.addHeader("wdt", AppContext.getInstance().getAppPreferencesHelper().getToken());
        builderHeader.addHeader("dt", "android");

        RequestBody requestBody = request.body();
        HttpUrl.Builder modifiedUrlBuilder = request.url().newBuilder();
        HttpUrl modifiedUrl;
        String method = request.method();
        Log.d("请求token", AppContext.getInstance().getAppPreferencesHelper().getToken()+"");
        if ("GET".equals(method)) {
            Log.d("请求GET",  modifiedUrlBuilder.build()+"");
        //    modifiedUrlBuilder.addQueryParameter("token", AppContext.getInstance().getAppPreferencesHelper().getKeyValue("token")+"");
            modifiedUrl = modifiedUrlBuilder.build();
            return chain.proceed(request.newBuilder().url(modifiedUrl).build());
        } else if (request.body() instanceof FormBody) {
            Request.Builder requestBuilder = request.newBuilder();
            FormBody.Builder newFormBody = new FormBody.Builder();
            FormBody oldFormBody = (FormBody) request.body();
            if (oldFormBody != null) {
                for (int i = 0; i < oldFormBody.size(); i++) {
                    newFormBody.addEncoded(oldFormBody.encodedName(i), oldFormBody.encodedValue(i));
                }
            }
            requestBuilder.method(request.method(), newFormBody.build());
            request = requestBuilder.build();
            return chain.proceed(request);
        } else if (request.body().contentType().subtype().equalsIgnoreCase("json")) {
            String body = null;
            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                body = buffer.readString(charset);
            }

            if(NET_IS_LOCAL){
                //去掉加密key
                String noSignBody = body;
                try {
                    Log.d("请求body=",noSignBody+"");
                    JSONObject jsonObject = new JSONObject(noSignBody);
                  //  jsonObject.put("token", AppContext.getInstance().getAppPreferencesHelper().getKeyValue("token")+"");
                    if(!UIUtils.isEmpty(jsonObject)){
                        String keyJson = jsonObject.optString("wdk");
                        if(!UIUtils.isEmpty(keyJson))noSignBody = keyJson;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), noSignBody);
                Request.Builder requestBuilder = request.newBuilder();
                requestBuilder.method(request.method(), requestBody1);
                request = requestBuilder.build();
                return chain.proceed(request);
            }else {
                //body添加公用体
                String newJsonBody = "";
                try {
                    Log.d("newJsonBody1=",body+"");
                    JSONObject jsonObject = new JSONObject(body);
                    // jsonObject.put("token", AppContext.getInstance().getAppPreferencesHelper().getKeyValue("token")+"");
                    newJsonBody = jsonObject.toString();
                    Log.d("newJsonBody2=",newJsonBody+"");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.d("请求body", body+"");
                RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), body);
                //TODO add param
                Request.Builder requestBuilder = request.newBuilder();
                requestBuilder.method(request.method(), requestBody1);
                request = requestBuilder.build();
                return chain.proceed(request);
            }
        }
        return chain.proceed(request);
    }
}
